package com.coder.books.thinkinjava.io;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

import static com.coder.util.Print.print;
import static com.coder.util.Print.println;

/**
 * 内存映射文件
 *
 * @author yuhushuan
 * @date 2020/8/29 11:59
 */
public class LargeMappedFiles {
    static int length = 0x8FFFFFF;// 128 MB

    public static void main(String[] args) throws IOException {
        MappedByteBuffer out = new RandomAccessFile("books/test.data", "rw").getChannel()
                .map(FileChannel.MapMode.READ_WRITE, 0, length);
        for (int i = 0; i < length; i++) {
            out.put((byte) 'x');
        }
        println("Finished writing");
        for (int i = length / 2; i < length / 2 + 6; i++) {
            print((char) out.get(i));
        }
    }
}
